<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getUserProfile, updateUserProfile, getUserStats, isUserVIP, upgradeToVIP, getUserAchievements, getRecentGames, ACHIEVEMENT_TYPES } from '../services/UserService.js'

const router = useRouter()
const username = ref('')
const email = ref('')
const avatar = ref('')
const bio = ref('')
const isVIP = ref(false)
const vipExpiry = ref('')
const stats = ref({
  totalGames: 0,
  reactionTests: 0,
  aimPractices: 0,
  bestReactionTime: 9999,
  highestScore: 0
})
const achievements = ref([])
const recentGames = ref([])
const editing = ref(false)
const error = ref('')
const success = ref('')

onMounted(() => {
  // 检查登录状态
  const loggedIn = localStorage.getItem('isLoggedIn') === 'true'
  if (!loggedIn) {
    router.push('/login')
    return
  }
  
  // 获取用户名
  const storedUsername = localStorage.getItem('username')
  if (storedUsername) {
    username.value = storedUsername
    loadUserProfile(storedUsername)
    loadUserStats(storedUsername)
    checkVIPStatus(storedUsername)
    loadUserAchievements(storedUsername)
    loadRecentGames(storedUsername)
  }
})

// 加载用户资料
const loadUserProfile = (userName) => {
  const profile = getUserProfile(userName)
  if (profile) {
    email.value = profile.email || ''
    avatar.value = profile.avatar || ''
    bio.value = profile.bio || ''
  }
}

// 加载用户统计数据
const loadUserStats = (userName) => {
  const userStats = getUserStats(userName)
  if (userStats) {
    stats.value = userStats
  }
}

// 加载用户成就
const loadUserAchievements = (userName) => {
  const userAchievements = getUserAchievements(userName)
  achievements.value = userAchievements
}

// 加载最近游戏记录
const loadRecentGames = (userName) => {
  const userRecentGames = getRecentGames(userName)
  recentGames.value = userRecentGames
}

// 检查VIP状态
const checkVIPStatus = (userName) => {
  const vipStatus = isUserVIP(userName)
  isVIP.value = vipStatus.isVIP
  vipExpiry.value = vipStatus.expiry || ''
}

// 切换编辑模式
const toggleEdit = () => {
  editing.value = !editing.value
  error.value = ''
  success.value = ''
}

// 保存用户资料
const saveProfile = () => {
  const result = updateUserProfile(username.value, {
    email: email.value,
    avatar: avatar.value,
    bio: bio.value
  })
  
  if (result.success) {
    success.value = result.message
    editing.value = false
    // 3秒后清除成功消息
    setTimeout(() => {
      success.value = ''
    }, 3000)
  } else {
    error.value = result.message
  }
}

// 跳转到VIP充值页面
const upgradeVIP = () => {
  router.push('/vip-recharge')
}

// 返回游戏页面
const goToGames = () => {
  router.push('/games')
}

// 退出登录
const logout = () => {
  localStorage.removeItem('isLoggedIn')
  localStorage.removeItem('username')
  router.push('/login')
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取成就提示信息
const getAchievementHint = (achievementName) => {
  const hints = {
    [ACHIEVEMENT_TYPES.FIRST_GAME]: '完成您的第一场游戏',
    [ACHIEVEMENT_TYPES.TEN_GAMES]: '累计完成10场游戏',
    [ACHIEVEMENT_TYPES.BEST_REACTION]: '获得您的第一个反应时间记录',
    [ACHIEVEMENT_TYPES.HIGH_SCORE]: '获得您的第一个游戏高分',
    [ACHIEVEMENT_TYPES.VIP_MEMBER]: '升级为VIP会员'
  }
  return hints[achievementName] || ''
}
</script>

<template>
  <div class="profile-container">
    <div class="profile-header">
      <div class="avatar-section">
        <div v-if="avatar" class="avatar" :style="{ backgroundImage: `url(${avatar})` }"></div>
        <span v-else class="avatar-placeholder">{{ username.charAt(0).toUpperCase() }}</span>
        <div v-if="isVIP" class="vip-badge">
          <span class="vip-icon">⭐</span>
          <span class="vip-text">VIP</span>
        </div>
      </div>
      <div class="user-info">
        <h1>{{ username }}<span v-if="isVIP" class="vip-tag">VIP</span></h1>
        <p v-if="email">{{ email }}</p>
        <p v-if="bio" class="bio">{{ bio }}</p>
        <div class="profile-actions">
          <button v-if="!editing" class="edit-button" @click="toggleEdit">编辑资料</button>
          <button v-if="!isVIP" class="vip-button" @click="upgradeVIP">升级VIP</button>
          <button class="games-button" @click="goToGames">返回游戏</button>
          <button class="logout-button" @click="logout">退出登录</button>
        </div>
      </div>
    </div>
    
    <!-- 编辑资料表单 -->
    <div v-if="editing" class="edit-profile-form">
      <h2>编辑个人资料</h2>
      <div class="form-group">
        <label for="email">邮箱</label>
        <input
          id="email"
          type="email"
          v-model="email"
          placeholder="请输入邮箱"
          class="form-input"
        />
      </div>
      <div class="form-group">
        <label for="avatar">头像URL</label>
        <input
          id="avatar"
          type="text"
          v-model="avatar"
          placeholder="请输入头像图片URL"
          class="form-input"
        />
      </div>
      <div class="form-group">
        <label for="bio">个人简介</label>
        <textarea
          id="bio"
          v-model="bio"
          placeholder="请输入个人简介"
          class="form-textarea"
          rows="3"
        ></textarea>
      </div>
      <div class="form-actions">
        <button class="save-button" @click="saveProfile">保存</button>
        <button class="cancel-button" @click="toggleEdit">取消</button>
      </div>
    </div>
    
    <!-- 游戏统计数据 -->
    <div class="game-stats">
      <h2>游戏统计</h2>
      <div class="stats-grid">
        <div class="stat-item">
          <div class="stat-value">{{ stats.totalGames }}</div>
          <div class="stat-label">总游戏次数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.reactionTests }}</div>
          <div class="stat-label">反应测试</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.aimPractices }}</div>
          <div class="stat-label">瞄准练习</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.bestReactionTime !== 9999 ? stats.bestReactionTime : '暂无' }} ms</div>
          <div class="stat-label">最佳反应时间</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.highestScore }}</div>
          <div class="stat-label">最高得分</div>
        </div>
      </div>
    </div>
    
    <!-- VIP信息 -->
    <div v-if="isVIP" class="vip-info">
      <h2>VIP特权</h2>
      <ul class="vip-benefits">
        <li>专属VIP标识</li>
        <li>解锁所有游戏难度</li>
        <li>无广告体验</li>
        <li>优先参与新游戏测试</li>
        <li>更多个性化设置</li>
      </ul>
      <p class="vip-expiry" v-if="vipExpiry">VIP有效期至: {{ vipExpiry }}</p>
    </div>
    
    <!-- 成就系统 -->
    <div class="achievements-section">
      <h2>我的成就</h2>
      <div v-if="achievements.length === 0" class="no-achievements">
        <p>您还没有解锁任何成就，快去玩游戏解锁吧！</p>
      </div>
      <div v-else class="achievements-grid">
        <div v-for="achievement in achievements" :key="achievement.type" class="achievement-item">
          <div class="achievement-icon">🏆</div>
          <div class="achievement-info">
            <div class="achievement-name">{{ achievement.type }}</div>
            <div class="achievement-date">{{ formatDate(achievement.unlockedAt) }}</div>
          </div>
        </div>
      </div>
      
      <!-- 未解锁成就 -->
      <div class="locked-achievements">
        <h3>待解锁成就</h3>
        <div class="achievements-grid">
          <div v-for="(name, key) in ACHIEVEMENT_TYPES" :key="key" 
               v-if="!achievements.some(a => a.type === name)" class="achievement-item locked">
            <div class="achievement-icon locked">🔒</div>
            <div class="achievement-info">
              <div class="achievement-name">{{ name }}</div>
              <div class="achievement-hint">{{ getAchievementHint(name) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 最近游戏记录 -->
    <div class="recent-games-section">
      <h2>最近游戏记录</h2>
      <div v-if="recentGames.length === 0" class="no-recent-games">
        <p>您还没有游戏记录，快去玩游戏吧！</p>
      </div>
      <div v-else class="recent-games-table">
        <table>
          <thead>
            <tr>
              <th>游戏类型</th>
              <th>得分</th>
              <th>反应时间</th>
              <th>时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="game in recentGames" :key="game.id">
              <td>{{ game.type === 'reaction' ? '反应测试' : '瞄准练习' }}</td>
              <td>{{ game.score }}</td>
              <td>{{ game.reactionTime ? game.reactionTime + ' ms' : '-' }}</td>
              <td>{{ formatDate(game.date) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    
    <!-- 消息提示 -->
    <div v-if="error" class="error-message">{{ error }}</div>
    <div v-if="success" class="success-message">{{ success }}</div>
  </div>
</template>

<style scoped>
.profile-container {
  min-height: 100vh;
  padding: 2rem;
  background: transparent;
  color: white;
  font-family: 'Arial', sans-serif;
  position: relative;
  z-index: 2;
}

.profile-header {
  display: flex;
  gap: 2rem;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 2rem;
  backdrop-filter: blur(10px);
}

.avatar-section {
  position: relative;
}

.avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background-size: cover;
  background-position: center;
  border: 3px solid rgba(255, 255, 255, 0.3);
}

.avatar-placeholder {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 3rem;
  font-weight: bold;
  border: 3px solid rgba(255, 255, 255, 0.3);
}

.vip-badge {
  position: absolute;
  bottom: 0;
  right: 0;
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #333;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.vip-icon {
  font-size: 1.2rem;
}

.user-info {
  flex: 1;
}

.user-info h1 {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
}

.vip-tag {
  color: #ffd700;
  font-size: 1.5rem;
}

.user-info p {
  font-size: 1.1rem;
  opacity: 0.9;
  margin-bottom: 0.5rem;
}

.bio {
  font-style: italic;
  margin-top: 1rem !important;
  line-height: 1.6;
}

.profile-actions {
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
}

.edit-button, .vip-button, .logout-button {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: bold;
  transition: all 0.3s ease;
}

.edit-button {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
}

.edit-button:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

.vip-button {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #333;
}

.vip-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(255, 215, 0, 0.4);
}

.games-button {
  background-color: #43a047;
  border: none;
  color: white;
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-right: 1rem;
}

.games-button:hover {
  background-color: #388e3c;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(67, 160, 71, 0.3);
}

.logout-button {
  background-color: rgba(255, 107, 107, 0.8);
  color: white;
}

.logout-button:hover {
  background-color: rgba(255, 107, 107, 1);
}

/* 编辑资料表单 */
.edit-profile-form {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 2rem;
  backdrop-filter: blur(10px);
}

.edit-profile-form h2 {
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
  font-size: 1rem;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  background-color: rgba(255, 255, 255, 0.1);
  color: white;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: rgba(255, 255, 255, 0.5);
  background-color: rgba(255, 255, 255, 0.15);
}

.form-input::placeholder, .form-textarea::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.form-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 2rem;
}

.save-button, .cancel-button {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: bold;
  transition: all 0.3s ease;
}

.save-button {
  background-color: #4ecdc4;
  color: white;
}

.save-button:hover {
  background-color: #45b7aa;
}

.cancel-button {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
}

.cancel-button:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

/* 游戏统计 */
.game-stats {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 2rem;
  backdrop-filter: blur(10px);
}

.game-stats h2 {
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 1.5rem;
}

.stat-item {
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 1.5rem;
  text-align: center;
  transition: all 0.3s ease;
}

.stat-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
  transform: translateY(-3px);
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 0.5rem;
  color: #4ecdc4;
}

.stat-label {
  font-size: 0.9rem;
  opacity: 0.9;
}

/* VIP信息 */
.vip-info {
  background: linear-gradient(135deg, rgba(255, 215, 0, 0.1), rgba(255, 237, 78, 0.1));
  border: 1px solid rgba(255, 215, 0, 0.3);
  border-radius: 12px;
  padding: 2rem;
  backdrop-filter: blur(10px);
}

.vip-info h2 {
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
  color: #ffd700;
}

.vip-benefits {
  list-style-type: none;
  padding: 0;
  margin-bottom: 1.5rem;
}

.vip-benefits li {
  padding: 0.75rem 0;
  padding-left: 2rem;
  position: relative;
  font-size: 1.1rem;
}

.vip-benefits li:before {
  content: '✓';
  position: absolute;
  left: 0;
  color: #ffd700;
  font-weight: bold;
}

.vip-expiry {
  font-size: 1rem;
  opacity: 0.9;
  text-align: right;
  font-style: italic;
}

/* 消息提示 */
.error-message {
  background-color: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
  padding: 1rem;
  border-radius: 6px;
  margin-top: 1rem;
  text-align: center;
}

.success-message {
  background-color: rgba(78, 205, 196, 0.2);
  color: #4ecdc4;
  padding: 1rem;
  border-radius: 6px;
  margin-top: 1rem;
  text-align: center;
}

/* 成就系统样式 */
  .achievements-section {
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 12px;
    padding: 2rem;
    margin-bottom: 2rem;
    backdrop-filter: blur(10px);
  }
  
  .achievements-section h2 {
    font-size: 1.8rem;
    margin-bottom: 1.5rem;
  }
  
  .achievements-section h3 {
    font-size: 1.4rem;
    margin: 1.5rem 0 1rem;
    color: rgba(255, 255, 255, 0.8);
  }
  
  .no-achievements, .no-recent-games {
    text-align: center;
    padding: 2rem;
    color: rgba(255, 255, 255, 0.7);
    font-style: italic;
  }
  
  .achievements-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 1rem;
  }
  
  .achievement-item {
    background-color: rgba(255, 255, 255, 0.05);
    border-radius: 8px;
    padding: 1rem;
    display: flex;
    align-items: center;
    gap: 1rem;
    transition: all 0.3s ease;
    border: 1px solid rgba(78, 205, 196, 0.3);
  }
  
  .achievement-item:hover {
    background-color: rgba(255, 255, 255, 0.1);
    transform: translateY(-2px);
  }
  
  .achievement-item.locked {
    border-color: rgba(255, 255, 255, 0.1);
    opacity: 0.6;
  }
  
  .achievement-icon {
    font-size: 2rem;
    width: 48px;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .achievement-info {
    flex: 1;
  }
  
  .achievement-name {
    font-weight: bold;
    font-size: 1.1rem;
    margin-bottom: 0.25rem;
  }
  
  .achievement-date {
    font-size: 0.9rem;
    color: rgba(255, 255, 255, 0.7);
  }
  
  .achievement-hint {
    font-size: 0.9rem;
    color: rgba(255, 255, 255, 0.7);
    font-style: italic;
  }
  
  /* 最近游戏记录样式 */
  .recent-games-section {
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 12px;
    padding: 2rem;
    backdrop-filter: blur(10px);
  }
  
  .recent-games-section h2 {
    font-size: 1.8rem;
    margin-bottom: 1.5rem;
  }
  
  .recent-games-table {
    overflow-x: auto;
  }
  
  .recent-games-table table {
    width: 100%;
    border-collapse: collapse;
  }
  
  .recent-games-table th,
  .recent-games-table td {
    padding: 1rem;
    text-align: left;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  }
  
  .recent-games-table th {
    background-color: rgba(255, 255, 255, 0.05);
    font-weight: bold;
    color: #4ecdc4;
  }
  
  .recent-games-table tr:hover {
    background-color: rgba(255, 255, 255, 0.05);
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .profile-container {
      padding: 1rem;
    }
    
    .profile-header {
      flex-direction: column;
      align-items: center;
      text-align: center;
    }
    
    .user-info h1 {
      font-size: 2rem;
    }
    
    .profile-actions {
      justify-content: center;
      flex-wrap: wrap;
    }
    
    .stats-grid {
      grid-template-columns: 1fr 1fr;
    }
    
    .stat-value {
      font-size: 1.5rem;
    }
    
    .achievements-grid {
      grid-template-columns: 1fr;
    }
    
    .recent-games-table {
      font-size: 0.9rem;
    }
    
    .recent-games-table th,
    .recent-games-table td {
      padding: 0.75rem;
    }
  }
</style>